<template>
  <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
      @onCreated="handleCreated" @onChange="handleChange" />
  </div>

</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, inject } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const baseUrl = inject('baseUrl')
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const toolbarConfig = {
  excludeKeys:['uploadVideo']
}
const mode = ref('default')
const editorConfig = { placeholder: '请输入内容...' };
editorConfig.MENU_CONF = {}
// 上传图片
editorConfig.MENU_CONF['uploadImage'] = {
  server: baseUrl+'/api/upload',
  fieldName: 'img',
  // // 小于该值就插入 base64 格式（而不上传），默认为 0
  base64LimitSize: 5 * 1024, // 5kb
  // customInsert(res, insertFn) {
  //   console.log('上传图片', res);
  // },
}

// 记录富文本的内容
const valueHtml = ref('<p>hello</p>')
// 接收父组件传过来的值
const props = defineProps({
  modelValue: {
    type: String,
    required: true
  }
})
const emit = defineEmits(['update:model-value'])
// 在模板中不需要渲染这个变量，所有没有加ref
let initFinished = false

onMounted(() => {
  setTimeout(() => {
    valueHtml.value = props.modelValue
    initFinished = true
  }, 10);
})
// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;

  editor.destroy();
});
// 编辑器的回调函数
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
const handleChange = (editor) => {
  // console.log(editor.getHtml());
  // 修改完之后往父组件传
  if (initFinished) {
    emit('update:model-value', valueHtml.value)
  }
}
</script>

<style lang="scss" scoped>

</style>